package com.wiqer.job58;



import com.wiqer.job58.cglib.TargetInterceptor;
import com.wiqer.job58.cglib.TargetObject;
import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * RPC Client（Create RPC proxy）
 *
 * @author luxiaoxun
 * @author g-yu
 */
public class TaskContext {

    private  ThreadPoolExecutor threadPoolExecutor ;

    public TaskContext() {
        threadPoolExecutor = new ThreadPoolExecutor(16, 16,
                600L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1000));
    }
    public TaskContext(int corePoolSize,
                       int maximumPoolSize,
                       long keepAliveTime,
                       TimeUnit unit,
                       BlockingQueue<Runnable> workQueue) {
        threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                keepAliveTime, unit, workQueue);
    }
    @SuppressWarnings("unchecked")
    public  <T> T createService(Class<T> interfaceClass, ExpectTask task) {
        return (T) Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class<?>[]{interfaceClass},
                new ExpectTaskProxy<T>(interfaceClass, task)
        );
    }
    @SuppressWarnings("unchecked")
    public  <T> T createTask(Class<T> interfaceClass, ExpectTask task) {
        return (T) Proxy.newProxyInstance(
                TaskContext.class.getClassLoader(),
                new Class<?>[]{interfaceClass},
                new ExpectTaskProxy<T>(interfaceClass, task)
        );
    }
    @SuppressWarnings("unchecked")
    public <T> T createCglibProxy(Class<T> objClass, ExpectTaskProxy task){
        Enhancer enhancer =new Enhancer();
        enhancer.setSuperclass(objClass);
        enhancer.setCallback(task);
        return (T) enhancer.create();
    }


    public  void submit(Runnable task) {
        threadPoolExecutor.submit(task);
    }


}


